package com.nettools.intercepter;

import android.util.Log;

import com.fileoperation.user.UserInfo;
import com.nettools.Constants;
import com.nettools.NetUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2016-12-21.
 */

public class TokenInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response;
        Log.w("TokenInterceptor", "pre url = " + request.url().toString());
        if (!request.url().toString().equals(Constants.LOGIN)) {
            Log.w("TokenInterceptor", "开始加accesstoken");
            HttpUrl.Builder builder = request.url().newBuilder();
            builder.addQueryParameter("access_token", UserInfo.getInstance().getAccessToken());
            Log.w("TokenInterceptor", "加完了之后 = " + builder.build().toString());
            response = chain.proceed(request.newBuilder().url(builder.build()).build());
        } else {
            response = chain.proceed(request);
        }

        try {
            MediaType mediaType = response.body().contentType();
            String content = response.body().string();
            if (isTokenExpired(content)) {
                Log.w("TokenInterceptor", "token过期了");
                NetUtils.getInstance().refreshAccessToken();

                HttpUrl.Builder urlBuilder = request.url().newBuilder();
                urlBuilder.setQueryParameter("access_token", UserInfo.getInstance().getAccessToken());
                Request newRequest = chain.request().newBuilder().url(urlBuilder.build())
                        .build();
                Response newResponse = chain.proceed(newRequest);
                return newResponse;

            }else {

                return response.newBuilder()
                        .body(ResponseBody.create(mediaType, content))
                        .build();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return response;
    }


    private boolean isTokenExpired(String response) throws IOException, JSONException {
//        JSONObject jsonObject = new JSONObject(response);
//        if (jsonObject.optInt(Constants.CODE) == -15) {
//            return true;
//        }
//        return false;
        return true;
    }
}
